<template>
  <div>
    <DynamicTable
      ref="dynamicTableRef"
      row-key="id"
      :header-title="$t('routes.system.system.user.list')"
      :data-request="loadData"
      :columns="columns"
      bordered
      size="small"
      :showIndex="false"
      :fetch-config="{ listField: 'data', totalField: 'count' }"
    >
      <template #toolbar>
        <a-button v-if="canAdd" type="primary" @click="add">
          {{ $t('common.add') }}
        </a-button>
      </template>
    </DynamicTable>
  </div>
</template>
<script lang="tsx" setup>
  import { ref } from 'vue'
  import { message } from 'ant-design-vue'
  import { DynamicTable } from '@/components/core/dynamic-table'
  import { useFormModal } from '@/hooks/useModal/useFormModal'
  import type { FormSchema } from '@/components/core/schema-form/src/types/form'
  import type { TableColumn } from '@/components/core/dynamic-table'
  import { useI18n } from '@/hooks/useI18n'
  import {
    fetchAllRole,
    getUserList,
    addUser,
    deleteUser,
    updateUserPass,
  } from '@/api/middleSystem'
  import { ApiDescription, HttpMethod } from '@/utils/apiDescription'
  import canAccessView from '@/utils/accessCheck'

  defineOptions({
    name: 'User',
  })

  const canAdd = ref(canAccessView(new ApiDescription('/user', HttpMethod.Post)))
  const canUpdate = ref(
    canAccessView(new ApiDescription('/user/password/{userId}', HttpMethod.Put)),
  )
  const canDelete = ref(canAccessView(new ApiDescription('/user/{userId}', HttpMethod.Delete)))

  const { t } = useI18n()
  const dynamicTableRef = ref<InstanceType<typeof DynamicTable>>()

  /**
   * 表格列
   */
  const columns: TableColumn<any>[] = [
    {
      title: '昵称',
      dataIndex: 'nickname',
    },
    {
      title: '账号',
      dataIndex: 'account',
      hideInSearch: true,
    },
    {
      title: '电话号码',
      dataIndex: 'phone',
    },
    {
      title: '所属角色',
      dataIndex: 'roleId',
      formItemProps: {
        component: 'Select',
        componentProps: {
          showSearch: true,
          optionFilterProp: 'label',
          request: async () => {
            return (await fetchAllRole()).data.map((item: any) => {
              return { label: item.name, value: item.id }
            })
          },
        },
      },
      customRender: ({ record }) => {
        return record.role.name
      },
    },
    {
      title: '拥有服务',
      dataIndex: 'hasService',
      hideInSearch: true,
      customRender: ({ record }) => {
        if (record.role.roleTag?.length) {
          return <span style="color: #67c23a">是</span>
        } else {
          return <span>否</span>
        }
      },
    },
    {
      title: '操作',
      dataIndex: 'ACTION',
      hideInSearch: true,
      actions: ({ record }) => [
        {
          label: '修改密码',
          hide: !canUpdate.value,
          onClick: () => updatePassword(record),
        },
        {
          label: t('common.delete'),
          danger: true,
          hide: !canDelete.value,
          popConfirm: {
            title: t('column.confirmDel'),
            onConfirm: () => del(record),
          },
        },
      ],
    },
  ]

  /**
   * 加载数据
   */
  const loadData = async params => {
    const { nickname, roleId, pageIndex, pageSize, phone } = params
    const data = await getUserList(nickname, roleId, pageIndex, pageSize, phone)
    return data
  }

  const [showModal] = useFormModal()
  const formSchemas: FormSchema[] = [
    {
      field: 'nickname',
      component: 'Input',
      label: '姓名',
      rules: [{ required: true }],
    },
    {
      field: 'phone',
      component: 'Input',
      label: '电话',
      rules: [{ required: true }],
    },
    {
      field: 'account',
      component: 'Input',
      label: '账号',
      rules: [{ required: true }],
    },
    {
      field: 'password',
      component: 'Input',
      label: '密码',
      rules: [{ required: true }],
    },
    {
      field: 'roleId',
      component: 'Select',
      label: '角色',
      rules: [{ required: true }],
      componentProps: {
        showSearch: true,
        optionFilterProp: 'label',
        request: async () => {
          return (await fetchAllRole()).data.map((item: any) => {
            return { label: item.name, value: item.id }
          })
        },
      },
    },
  ]

  /**
   * 新增用户
   */
  const add = async () => {
    const [formRef] = await showModal({
      modalProps: {
        title: t('common.add'),
        width: 700,
        onFinish: async values => {
          const { account, password, roleId, nickname, phone } = values
          await addUser(account, password, roleId, nickname, phone, {})
          message.success('操作成功')
          dynamicTableRef.value?.reload()
        },
      },
      formProps: {
        labelWidth: 100,
        schemas: formSchemas,
      },
    })
  }

  /**
   * 修改密码
   */
  const updatePassword = async record => {
    const [formRef] = await showModal({
      modalProps: {
        title: '修改密码',
        width: 700,
        onFinish: async values => {
          const { password } = values
          await updateUserPass(record.id, password)
          message.success('操作成功')
          dynamicTableRef.value?.reload()
        },
      },
      formProps: {
        labelWidth: 100,
        schemas: [
          {
            field: 'password',
            component: 'Input',
            label: '新密码',
            rules: [{ required: true }],
          },
        ],
      },
    })
  }

  /**
   * 删除
   */
  const del = async record => {
    await deleteUser(record.id)
    message.success('操作成功')
    dynamicTableRef.value?.reload()
  }
</script>
